package com.example.base.mvvm

import android.util.Log
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.base.entity.Res
import com.google.gson.Gson
import kotlinx.coroutines.launch
import okhttp3.MediaType
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.RequestBody
import java.text.SimpleDateFormat

open class BaseViewModel : ViewModel() {

    fun <T> httpRequest (s:suspend ()->Res<T>,success:(T)->Unit) {
        viewModelScope.launch {
            try {
                val res = s.invoke()
                if (res.code == 200) {
                    success(res.data)
                }else {
                    Log.i("===", res.message)
                }
            }catch (e:Exception) {
                Log.i("===", e.message.toString())
            }
        }
    }

    fun <T> roomRequest (s:suspend ()->T,success:(T)->Unit) {
        viewModelScope.launch {
            try {
                val res = s.invoke()
                if (res != null) {
                    success(res)
                }else {
                    Log.i("===", "操作不正确")
                }
            }catch (e:Exception) {
                Log.i("===", e.message.toString())
            }
        }
    }

    fun toBody(any: Any):RequestBody{
        val json = Gson().toJson(any)
        val requestBody = RequestBody.create("application/json;charset=utf-8".toMediaTypeOrNull(), json)
        return requestBody
    }

    fun getDateTimeString(time:Long):String{
        return SimpleDateFormat("yyyyMMddHHmmss").format(time)
    }

    fun getDataTime(time: Long):String{
        return SimpleDateFormat("yyy-MM-dd HH:mm:ss").format(time)
    }

    fun getTime(time: Long):String{
        return SimpleDateFormat("HH:mm:ss").format(time)
    }

    fun getData(time: Long):String{
        return SimpleDateFormat("yyyy-MM-dd").format(time)
    }

    fun getMonth():String {
        return SimpleDateFormat("MM").format(System.currentTimeMillis())
    }

    fun getYear():String {
        return SimpleDateFormat("yyyy").format(System.currentTimeMillis())
    }
}